﻿//用MSWord替代过长的引用类型
using MSWord = Microsoft.Office.Interop.Word;
using System.Runtime.InteropServices;
namespace ToWordTry
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //文件路径变量
            object path;
            //文本内容变量 ///这里应该是用string当作文本输入吧？
            string strContent;
            //word应用程序变量
            MSWord.Application wordApp;
            //Word文档变量
            MSWord.Document wordDoc;

            //初始化文件路径并生成文件
            path = Environment.CurrentDirectory + "MyWord_Print.doc";
            wordApp = new MSWord.Application();
            //使文档可见
            wordApp.Visible = true;
            //如果文档存在那么删除
            if (File.Exists((string)path))
                File.Delete((string)path);
            //由于使用COM库，一些变量要用Missing.Value来替代
            //Missing.Value 是System.Reflection中的调用
            Object Nothing = System.Reflection.Missing.Value;
            //用wordApp初始化worDoc，即在APP中初始化生成一个文稿
            wordDoc = wordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing);


            #region  页面设置、页眉图片和文字设置，最后跳出页眉设置
            //设置纸张大小为A4
            wordDoc.PageSetup.PaperSize = MSWord.WdPaperSize.wdPaperA4;
            //设置纸张方向为垂直方向
            wordDoc.PageSetup.Orientation = MSWord.WdOrientation.wdOrientPortrait;
            //设置上下左右边缘页边距以及页眉位置
            wordDoc.PageSetup.TopMargin = 57.0f;
            wordDoc.PageSetup.BottomMargin = 57.0f;
            wordDoc.PageSetup.LeftMargin = 57.0f;
            wordDoc.PageSetup.RightMargin = 57.0f;
            //设置页眉边距
            wordDoc.PageSetup.HeaderDistance = 30.0f;
            //视图样式（普通视图，即页面视图样式）
            wordApp.ActiveWindow.View.Type = MSWord.WdViewType.wdNormalView;
            /*
            //进入页眉设置，其中页眉边距设置已经在页面设置中完成
            wordApp.ActiveWindow.View.SeekView = MSWord.WdSeekView.wdSeekPrimaryHeader;
            //页眉中的文字右对齐
            wordApp.Selection.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphRight;
            //插入页眉图片（测试结果图片未插入成功）
            wordApp.Selection.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphCenter;
            string headerfile = @"C:\Users\Ma Chenhe\Desktop\Temp\test.jpg";
            MSWord.InlineShape shape1 = wordApp.ActiveWindow.ActivePane.Selection.InlineShapes.AddPicture(headerfile,ref Nothing,ref Nothing,ref Nothing);
            shape1.Height = 5;  //强行设置无效，图片没有按设置的缩放比例改变
            shape1.Width = 20;
            wordApp.ActiveWindow.ActivePane.Selection.InsertAfter("  文档页眉");//页眉的图片后面追加几个字
            //去掉页眉的横线
            wordApp.ActiveWindow.ActivePane.Selection.ParagraphFormat.Borders[MSWord.WdBorderType.wdBorderBottom].LineStyle = MSWord.WdLineStyle.wdLineStyleNone;
            wordApp.ActiveWindow.ActivePane.Selection.Borders[MSWord.WdBorderType.wdBorderBottom].Visible = false;
            //退出页眉设置
            wordApp.ActiveWindow.ActivePane.View.SeekView = MSWord.WdSeekView.wdSeekMainDocument;
            */
            #endregion

            #region 页码设置并添加页码
            //为当前页添加页码      //获取当前页的页码
            MSWord.PageNumbers pns = wordApp.Selection.Sections[1].Headers[MSWord.WdHeaderFooterIndex.wdHeaderFooterEvenPages].PageNumbers;
            //设置页码风格，是Dash形状还是圆形的
            pns.NumberStyle = MSWord.WdPageNumberStyle.wdPageNumberStyleNumberInDash;
            pns.HeadingLevelForChapter = 0;
            pns.IncludeChapterNumber = false;
            pns.RestartNumberingAtSection = false;
            pns.StartingNumber = 0;     //开始页页码
            //将页码设置在页脚中间
            object pagenmbetal = MSWord.WdPageNumberAlignment.wdAlignPageNumberCenter;
            object first = true;
            wordApp.Selection.Sections[1].Footers[MSWord.WdHeaderFooterIndex.wdHeaderFooterEvenPages].PageNumbers.Add(ref pagenmbetal, ref first);
            #endregion

            #region 行间距与缩进、文本字体、字号、加粗、斜体、颜色、下划线、下划线颜色设置
            //设置文档行间距
            wordApp.Selection.ParagraphFormat.LineSpacing = 16f;
            //设置首行缩进长度
            wordApp.Selection.ParagraphFormat.FirstLineIndent = 30;
            //写入普通文本，用转义字符换行
            strContent = "我是普通文本\n";
            wordDoc.Paragraphs.Last.Range.Text = strContent;
            wordDoc.Paragraphs.Last.Range.Text = "我再加一行试试，这里不加\"\n\"";
            //直接添加段，不是覆盖（+=）
            wordDoc.Paragraphs.Last.Range.Text += "不会覆盖的";
            //添加在此段文字的后面，不是新段落
            wordDoc.Paragraphs.Last.Range.InsertAfter("这是后面的内容\n");
            //将文档的前4个字替换成"哥是替换文字"，并将其颜色设置为红色
            object start = 0;
            object end = 4;
            MSWord.Range rang = wordDoc.Range(ref start, ref end);
            rang.Font.Color = MSWord.WdColor.wdColorRed;
            rang.Text = "哥是替换文字";
            wordDoc.Range(ref start, ref end);

            //写入黑体文本
            object unite = MSWord.WdUnits.wdStory;
            wordApp.Selection.EndKey(ref unite, ref Nothing);//将光标移到文本末尾
            wordApp.Selection.ParagraphFormat.FirstLineIndent = 0;//取消首行缩进的长度
            strContent = "这是黑体文本\n";
            wordDoc.Paragraphs.Last.Range.Font.Name = "黑体";
            wordDoc.Paragraphs.Last.Range.Text = strContent;

            //写入加粗文本
            strContent = "这是粗体文本\n"; //
            wordApp.Selection.EndKey(ref unite, ref Nothing);//这一句不加，有时候好像也不出问题，不过还是加了安全
            wordDoc.Paragraphs.Last.Range.Font.Bold = 1;
            wordDoc.Paragraphs.Last.Range.Text = strContent;

            //写入15号字体文本
            strContent = "我这个文本的字号是15号，而且是宋体\n";
            wordApp.Selection.EndKey(ref unite, ref Nothing);
            wordDoc.Paragraphs.Last.Range.Font.Size = 15;
            wordDoc.Paragraphs.Last.Range.Font.Name = "宋体";
            wordDoc.Paragraphs.Last.Range.Text = strContent;

            //写入斜体文本
            strContent = "我是斜体字文本\n";
            wordApp.Selection.EndKey(ref unite, ref Nothing);
            wordDoc.Paragraphs.Last.Range.Font.Italic = 1;
            wordDoc.Paragraphs.Last.Range.Text = strContent;

            //写入蓝色文本
            strContent = "我是蓝色的文本\n";
            wordApp.Selection.EndKey(ref unite, ref Nothing);
            wordDoc.Paragraphs.Last.Range.Font.Color = MSWord.WdColor.wdColorBlue;
            wordDoc.Paragraphs.Last.Range.Text = strContent;

            //写入下划线文本
            strContent = "我是下划线文本\n";
            wordApp.Selection.EndKey(ref unite, ref Nothing);
            wordDoc.Paragraphs.Last.Range.Font.Underline = MSWord.WdUnderline.wdUnderlineThick;
            wordDoc.Paragraphs.Last.Range.Text = strContent;

            //写入红色下画线文本
            strContent = "我是点线下划线，并且下划线是红色的\n";
            wordApp.Selection.EndKey(ref unite, ref Nothing);
            wordDoc.Paragraphs.Last.Range.Font.Underline = MSWord.WdUnderline.wdUnderlineDottedHeavy;
            wordDoc.Paragraphs.Last.Range.Font.UnderlineColor = MSWord.WdColor.wdColorRed;
            wordDoc.Paragraphs.Last.Range.Text = strContent;

            //取消下划线，并且将字号调整为12号
            strContent = "我不要下划线了，并且设置字号为12号，黑色不要斜体\n";
            wordApp.Selection.EndKey(ref unite, ref Nothing);
            wordDoc.Paragraphs.Last.Range.Font.Size = 12;
            wordDoc.Paragraphs.Last.Range.Font.Underline = MSWord.WdUnderline.wdUnderlineNone;
            wordDoc.Paragraphs.Last.Range.Font.Color = MSWord.WdColor.wdColorBlack;
            wordDoc.Paragraphs.Last.Range.Font.Italic = 0;
            wordDoc.Paragraphs.Last.Range.Text = strContent;

            #endregion

            #region 插入图片、居中显示，设置图片的绝对尺寸和缩放尺寸，并给图片添加标题
            //将光标移动到文档末尾
            wordApp.Selection.EndKey(ref unite, ref Nothing);
            //图片文件的路径，这是当前路径加上图片文件名，图片要放在这个目录下
            string filename = Environment.CurrentDirectory + "\\test.jpg";
            //要向Word文档中插入图片的位置
            Object range = wordDoc.Paragraphs.Last.Range;
            
            //定义该插入的图片是否为外部链接
            Object linkToFile = false;               //默认,这里貌似设置为bool类型更清晰一些
            //定义要插入的图片是否随Word文档一起保存
            Object saveWithDocument = true;              //默认
            //使用InlineShapes.AddPicture方法(【即“嵌入型”】)插入图片
            wordDoc.InlineShapes.AddPicture(filename, ref linkToFile, ref saveWithDocument, ref range);
            //居中显示图片
            wordApp.Selection.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphCenter;

            //设置图片宽高的绝对大小

            //wordDoc.InlineShapes[1].Width = 200;
            //wordDoc.InlineShapes[1].Height = 150;            //按比例缩放大小

            wordDoc.InlineShapes[1].ScaleWidth = 100;//缩小到20% ？
            wordDoc.InlineShapes[1].ScaleHeight = 100;

            //在图下方居中添加图片标题
            wordDoc.Content.InsertAfter("\n");//这一句与下一句的顺序不能颠倒，原因还没搞透
            wordApp.Selection.EndKey(ref unite, ref Nothing);
            wordApp.Selection.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphCenter;
            wordApp.Selection.Font.Size = 10;//字体大小
            wordApp.Selection.TypeText("图1 测试图片\n");

            #endregion

            #region 添加表格，填充数据，设置表格行列宽高，合并单元格、添加表头斜线、给单元格添加图片
            //先增加一行间隔
            wordDoc.Content.InsertAfter("\n");//这一句和下一句数据不能颠倒
            wordApp.Selection.EndKey(ref unite, ref Nothing);//光标移动到文档末尾
            //新建一个表格
            wordApp.Selection.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphLeft;
            //object WdLine2 = MSWord.WdUnits.wdLine;//换一行;  
            //wordApp.Selection.MoveDown(ref WdLine2, 6, ref Nothing);//向下跨15行输入表格，这样表格就在文字下方了，不过这是非主流的方法

            //设置表格的行列数
            int tableRow = 6;
            int tableColumn = 6;

            //定义一个Word中的表格对象 
            MSWord.Table table = wordDoc.Tables.Add(wordApp.Selection.Range, tableRow, tableColumn, ref Nothing, ref Nothing);

            //默认创建的表格没有边框，修改属性使其带边框
            table.Borders.Enable = 1;   //这个值可以设大，如5，13等

            //表格索引从1开始
            wordDoc.Tables[1].Cell(1, 1).Range.Text = "列\n行";
            for (int i = 0; i < tableRow; i++)
            {
                for (int j = 0; j < tableColumn; j++)
                {
                    if (i == 1)
                    {
                        //填充每一列的标题，因为Word中表格序数从1开始，故要j+1
                        table.Cell(i, j + 1).Range.Text = "Column" + j;
                    }
                    if (j == 1)
                    {
                        //填充每一行的标题
                        table.Cell(i + 1, j).Range.Text = "Row" + i;
                    }
                    //填充表格的各个小格子
                    table.Cell(i + 1, j + 1).Range.Text = i + "行" + j + "列";
                }
            }

            //添加行
            table.Rows.Add(ref Nothing);
            //设置新增的这行表格的高度
            table.Rows[tableRow + 1].Height = 35;
            //向新添加的行的单元格中添加图片
            string FileName = Environment.CurrentDirectory + "\\test.jpg";
            object LinkToFile = false;
            object SaveWithDocument = true;
            object Anchor = table.Cell(tableRow + 1, tableColumn).Range;//选中要添加图片的单元格
            wordDoc.Application.ActiveDocument.InlineShapes.AddPicture(FileName, ref LinkToFile, ref SaveWithDocument, ref Anchor);

            //由于是本文档的第二张图，这里是InlineShapes[2]
            wordDoc.Application.ActiveDocument.InlineShapes[2].Width = 50;//图片宽度
            wordDoc.Application.ActiveDocument.InlineShapes[2].Height = 35;//图片高度

            //将图片设置为四周环绕型
            MSWord.Shape s = wordDoc.Application.ActiveDocument.InlineShapes[2].ConvertToShape();
            s.WrapFormat.Type = MSWord.WdWrapType.wdWrapSquare;

            //设置table样式
            //高度规则是行高有最低值下限
            table.Rows.HeightRule = MSWord.WdRowHeightRule.wdRowHeightAtLeast;
            //没看懂要设置什么
            table.Rows.Height = wordApp.CentimetersToPoints(float.Parse("0.8"));

            table.Range.Font.Size = 10.5F;
            table.Range.Font.Bold = 0;
            //表格文本居中
            table.Range.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphCenter;
            //文本垂直贴到底部
            table.Range.Cells.VerticalAlignment = MSWord.WdCellVerticalAlignment.wdCellAlignVerticalBottom;

            //设置table边框样式
            //表格外框双线
            table.Borders.OutsideLineStyle = MSWord.WdLineStyle.wdLineStyleDouble;
            //表格内框是单线
            table.Borders.InsideLineStyle = MSWord.WdLineStyle.wdLineStyleSingle;
            //加粗
            table.Rows[1].Range.Font.Bold = 1;
            table.Rows[1].Range.Font.Size = 12F;
            table.Cell(1, 1).Range.Font.Size = 10.5F;
            //所有单元格的高度
            wordApp.Selection.Cells.Height = 30;
            //除第一行外，其他行的行高都设置为20
            for (int i = 2; i < tableRow; i++)
            {
                table.Rows[i].Height = 20;
            }
            //将表格左上角的单元格里的文字（“行”和“列”）居右
            table.Cell(1, 1).Range.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphRight;
            //将表格左上角的单元格里面下面的“列”字移到左边，相比上一行就是将ParagraphFormat改成了Paragrphs[2].Format
            table.Cell(1, 1).Range.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphRight;
            //将第一列列宽设置为50
            table.Columns[1].Width = 50;
            //将其他列列宽设置为75
            for (int i = 2; i <= tableColumn; i++)
            {
                table.Columns[i].Width = 75;
            }
            //添加表头斜线，并设置表头的样式
            table.Cell(1, 1).Borders[MSWord.WdBorderType.wdBorderDiagonalDown].Visible = true;
            //设置颜色
            table.Cell(1, 1).Borders[MSWord.WdBorderType.wdBorderDiagonalDown].Color = MSWord.WdColor.wdColorRed;
            //设置宽度
            table.Cell(1, 1).Borders[MSWord.WdBorderType.wdBorderDiagonalDown].LineWidth = MSWord.WdLineWidth.wdLineWidth150pt;

            //合并单元格
            table.Cell(4, 4).Merge(table.Cell(4, 5));//横向合并
            table.Cell(2, 3).Merge(table.Cell(4, 3));//纵向合并
            #endregion

            //光标移动到文档末尾
            wordApp.Selection.EndKey(ref unite, ref Nothing);
            wordDoc.Content.InsertAfter("就写那么多吧！");

            //WdSaveFormat为Word的保存格式
            //作者说带Default是Word2007
            object format = MSWord.WdSaveFormat.wdFormatDocumentDefault;
            //将Word文档对象的内容保存为DOCX文档
            wordDoc.SaveAs2(ref path, ref format, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing);
            //看看是不是要打印
            //wordDoc.PrintOut();
            //关闭Word文档
            wordDoc.Close(ref Nothing, ref Nothing);
            wordApp.Quit(ref Nothing, ref Nothing, ref Nothing);
            Console.WriteLine(path + "创建完毕！");
            Console.ReadKey();

            //打开文档
            MSWord.Application app = new MSWord.Application();
            MSWord.Document doc = null;
            try
            {
                object unknow = Type.Missing;
                app.Visible = true;
                string str = Environment.CurrentDirectory + "\\MyWord_Print.doc";
                object file = str;
                doc = app.Documents.Open(ref file,
                    ref unknow, ref unknow, ref unknow, ref unknow,
                    ref unknow, ref unknow, ref unknow, ref unknow,
                    ref unknow, ref unknow, ref unknow, ref unknow,
                    ref unknow, ref unknow, ref unknow);
                string temp = doc.Paragraphs[1].Range.Text.Trim();
                Console.WriteLine("你输出temp干嘛？");
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            wordDoc = doc;
            wordDoc.Paragraphs.Last.Range.Text += "不写了";
            Console.ReadKey();
        }




    }
}